package com.yj.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.yj.dao.AcademyDao;
import com.yj.dao.BaseDao;
import com.yj.dao.ClassesDao;
import com.yj.dao.CourseDao;
import com.yj.dao.ScDao;
import com.yj.dao.StudentDao;
import com.yj.dao.TeacherDao;
import com.yj.dao.UserDao;
import com.yj.service.BaseService;

@SuppressWarnings("rawtypes")
@Service("baseService")
@Lazy(true)
public class BaseServiceImpl<T> implements BaseService<T> {
	
	private Class clazz;
	
	protected BaseDao baseDao;
	
	@Resource
	protected UserDao userDao;
	
	@Resource
	protected StudentDao studentDao;
	
	@Resource
	protected CourseDao courseDao;
	
	@Resource
	protected ScDao scDao;
	
	@Resource
	protected AcademyDao academyDao;
	
	@Resource
	protected ClassesDao classesDao;
	
	@Resource
	protected TeacherDao teacherDao;
	
	public BaseServiceImpl() {
		System.out.println("this代表的是当前调用构造方法的对象" + this);
		System.out.println("获取当前this对象的父类信息" + this.getClass().getSuperclass());
		System.out.println("获取当前this对象的父类信息(包括泛型信息)" + this.getClass().getGenericSuperclass());
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class)type.getActualTypeArguments()[0];
	}
	
	@PostConstruct
	public void init() {
		//根据clazz的类型，把不同的dao对象复制给baseDao对象
		String clazzName = clazz.getSimpleName();
		if(clazzName.equals("Student") || clazzName.equals("Course") || clazzName.equals("Sc") 
				|| clazzName.equals("Academy") || clazzName.equals("Classes") || clazzName.equals("Teacher")) {
			String clazzDao = clazzName.substring(0, 1).toLowerCase() 
					+ clazzName.substring(1) + "Dao";
			try {
				Field clazzField = this.getClass().getSuperclass().getDeclaredField(clazzDao);
				Field baseField = this.getClass().getSuperclass().getDeclaredField("baseDao");
				baseField.set(this, clazzField.get(this)); //baseDao就有值了
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void save(T t) {
		baseDao.save(t);
	}

	@SuppressWarnings("unchecked")
	@Override 
	public void update(T t) {
		baseDao.update(t);
	}

	@Override
	public void delete(Integer id) {
		baseDao.delete(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T get(Integer id) {
		return (T) baseDao.get(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> query() {
		return baseDao.query();
	}

}